package com.woniuxy.ticket.ticketmovie.exception;

import com.woniuxy.ticket.ticketmovie.entity.ResponseResult;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class TicketExceptionHandler {

    @ExceptionHandler(TypeNameExistException.class)
    public ResponseResult<Void> exceptionHandler(TypeNameExistException e) {
        return new ResponseResult<Void>(101, "类型名字重复！");
    }

    @ExceptionHandler(DataAccessException.class)
    public ResponseResult<Void> DataAccessExceptionHandler(DataAccessException e) {
        return new ResponseResult<>(500, "数据异常！");
    }

    /**
     * 抓取数据校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<Object> validateException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        if(result.hasFieldErrors()){
            Map<String, String> msg = new HashMap<>();
            result.getFieldErrors().forEach(c -> {
                msg.put(c.getField(), c.getDefaultMessage());
            });

            ResponseResult<Object> responseResult = new ResponseResult<>();
            responseResult.setStatusCode(102);
            responseResult.setMessage("无效参数");
            responseResult.setData(msg);
            return responseResult;
        }
        return null;
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseResult<Object> violationExceptionHandler(ConstraintViolationException e) {
        e.printStackTrace();
        Map<String, String> msg = new HashMap<String, String>();
        if (e.getConstraintViolations().size() > 0) {
            e.getConstraintViolations().forEach(c -> {
                String path = c.getPropertyPath().toString();
                msg.put(path.substring(path.lastIndexOf(".") + 1), c.getMessage());
            });
            ResponseResult<Object> responseResult = new ResponseResult<>();
            responseResult.setStatusCode(102);
            responseResult.setMessage("无效参数");
            responseResult.setData(msg);
            return responseResult;
        }
        return null;
    }
}
